package controllers;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import debugs.UserDebug;

import models.UserModel;
import entities.User;
import forms.UserForm;

public class ChangeAvatarServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		TreeMap check = new TreeMap();
		
		User user = (User) request.getAttribute("user_logged_in");
		if (user == null) {
			response.sendRedirect("/msg/require-login");
			return ;
		}
		
		try {
			user = (User) user.clone();
		} catch (CloneNotSupportedException e1) {
			//e1.printStackTrace();
		}
		
		request.setAttribute("user", user);
		request.setAttribute("check", check);
		request.setAttribute("form", "edit");
		try {
			request.getRequestDispatcher("/pages/change_avatar.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		UserModel userModel = UserModel.getInstance();
		User user = (User) request.getAttribute("user_logged_in");
		
		try {
			user = (User) user.clone();
		} catch (CloneNotSupportedException e1) {
			//e1.printStackTrace();
		}
		
		TreeMap forms = (TreeMap) UserForm.checkValidAvatar(request, user);
		user = (User) forms.get("user");
		TreeMap check = (TreeMap) forms.get("checkValid");
		//check = CaptchaForm.checkValid(request, check);
		
		if (check.size() == 0) {
			userModel.insert(user);
			
			HttpSession session = request.getSession();
			session.setAttribute("user_logged_in", user);
			session.setAttribute("success", "Update successfully!");
			
			response.sendRedirect("/profile/change-avatar");
		}
		
		request.setAttribute("user", user);
		request.setAttribute("check", check);
		request.setAttribute("form", "edit");
		try {
			request.getRequestDispatcher("/pages/change_avatar.jsp").forward(request, response);
		} catch (ServletException e) {
			//e.printStackTrace();
		}
	}
}
